<template>
  <div class="dicom-mpr-page">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2 class="page-title">DICOM MPR 三视图</h2>
        <span class="page-subtitle">多平面重建 (Multi-Planar Reconstruction)</span>
      </div>
      <div class="toolbar-right">
        <div class="connection-status">
          <span class="status-indicator" :class="{ 'connected': orthancConnected, 'disconnected': !orthancConnected }">
            {{ orthancConnected ? '🟢' : '🔴' }}
          </span>
          <span class="status-text">
            {{ orthancConnected ? 'Orthanc已连接' : 'Orthanc未连接' }}
          </span>
        </div>
        
        <button 
          class="sync-btn" 
          @click="toggleSync" 
          :class="{ 'active': syncEnabled }"
          :disabled="!volumeData"
        >
          {{ syncEnabled ? '🔗 同步开启' : '🔓 同步关闭' }}
        </button>
        
        <button 
          class="reset-btn" 
          @click="resetView"
          :disabled="!volumeData"
        >
          🔄 重置视图
        </button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧系列选择面板 -->
      <div class="series-panel">
        <div class="panel-header">
          <h3>系列选择</h3>
          <span class="series-count">{{ availableSeries.length }} 个系列</span>
        </div>
        
        <div class="series-list">
          <div 
            v-for="series in availableSeries" 
            :key="series.id"
            class="series-item"
            :class="{ 'active': selectedSeriesId === series.id }"
            @click="selectedSeriesId = series.id"
          >
            <div class="series-info">
              <div class="series-title">
                {{ series.MainDicomTags?.SeriesDescription || '未命名系列' }}
              </div>
              <div class="series-details">
                <span class="detail-item">{{ series.Instances?.length || 0 }} 张图像</span>
                <span class="detail-item">{{ series.MainDicomTags?.Modality || 'N/A' }}</span>
              </div>
              <div class="series-id">ID: {{ series.id.substring(0, 8) }}...</div>
            </div>
            <div v-if="selectedSeriesId === series.id" class="series-selected-icon">✓</div>
              </div>
              
          <div v-if="availableSeries.length === 0" class="empty-series">
            <div class="empty-icon">📁</div>
            <div class="empty-text">
              {{ orthancConnected ? '暂无可用系列' : '请先连接 Orthanc' }}
              </div>
              </div>
              </div>
              
        <div class="panel-footer">
          <button 
            @click="() => loadVolumeData(true)" 
            class="load-btn"
            :disabled="!selectedSeriesId || loading"
          >
            <span v-if="loading">
              <span class="loading-spinner">⏳</span>
              {{ loadingMessage }}
              <br>
              <span class="progress-text">{{ loadProgress }}%</span>
            </span>
            <span v-else>
              <span class="btn-icon">🚀</span>
              智能加载体数据
            </span>
                </button>
            </div>
          </div>
          
      <!-- 右侧MPR查看器 -->
      <div class="viewer-panel">
        <div v-if="!volumeData" class="empty-viewer">
          <div class="empty-content">
            <div class="empty-icon">🔲</div>
            <div class="empty-title">请选择并加载DICOM系列</div>
            <div class="empty-subtitle">
              系统将自动生成轴位、冠状位、矢状位三个正交平面视图
            </div>
          </div>
        </div>
        
        <div v-else class="mpr-viewer">
          <!-- MPR视图网格 -->
          <div class="mpr-grid">
            <!-- 轴位视图 (Axial) -->
            <div class="viewport axial-view">
              <div class="viewport-header">
                <h4>轴位 (Axial)</h4>
                <span class="slice-info">
                  {{ currentSlices.axial + 1 }} / {{ volumeData.dimensions[2] }}
                </span>
              </div>
              <div class="viewport-content" ref="axialViewport">
                <canvas 
                  ref="axialCanvas" 
                  class="dicom-canvas"
                  @wheel="onMouseWheel('axial', $event)"
                ></canvas>
                <div class="viewport-overlay">
                  <div class="orientation-labels">
                    <span class="label-top">A</span>
                    <span class="label-bottom">P</span>
                    <span class="label-left">R</span>
                    <span class="label-right">L</span>
                  </div>
                </div>
              </div>
              <div class="viewport-slider">
              <input 
                  v-model.number="currentSlices.axial" 
                type="range" 
                :min="0" 
                  :max="volumeData.dimensions[2] - 1"
                  @input="renderAxialView"
                class="slice-slider"
              >
            </div>
            </div>
            
            <!-- 冠状位视图 (Coronal) -->
            <div class="viewport coronal-view">
              <div class="viewport-header">
                <h4>冠状位 (Coronal)</h4>
                <span class="slice-info">
                  {{ currentSlices.coronal + 1 }} / {{ volumeData.dimensions[1] }}
                </span>
            </div>
              <div class="viewport-content" ref="coronalViewport">
                <canvas 
                  ref="coronalCanvas" 
                  class="dicom-canvas"
                  @wheel="onMouseWheel('coronal', $event)"
                ></canvas>
                <div class="viewport-overlay">
                  <div class="orientation-labels">
                    <span class="label-top">S</span>
                    <span class="label-bottom">I</span>
                    <span class="label-left">R</span>
                    <span class="label-right">L</span>
          </div>
                </div>
              </div>
              <div class="viewport-slider">
                <input 
                  v-model.number="currentSlices.coronal" 
                  type="range" 
                  :min="0" 
                  :max="volumeData.dimensions[1] - 1"
                  @input="renderCoronalView"
                  class="slice-slider"
                >
              </div>
                </div>
                
            <!-- 矢状位视图 (Sagittal) -->
            <div class="viewport sagittal-view">
              <div class="viewport-header">
                <h4>矢状位 (Sagittal)</h4>
                <span class="slice-info">
                  {{ currentSlices.sagittal + 1 }} / {{ volumeData.dimensions[0] }}
                </span>
                    </div>
              <div class="viewport-content" ref="sagittalViewport">
                <canvas 
                  ref="sagittalCanvas" 
                  class="dicom-canvas"
                  @wheel="onMouseWheel('sagittal', $event)"
                ></canvas>
                <div class="viewport-overlay">
                  <div class="orientation-labels">
                    <span class="label-top">S</span>
                    <span class="label-bottom">I</span>
                    <span class="label-left">A</span>
                    <span class="label-right">P</span>
                  </div>
                </div>
                </div>
              <div class="viewport-slider">
                <input 
                  v-model.number="currentSlices.sagittal" 
                  type="range" 
                  :min="0" 
                  :max="volumeData.dimensions[0] - 1"
                  @input="renderSagittalView"
                  class="slice-slider"
                >
              </div>
            </div>
          </div>
          
          <!-- 底部信息面板 -->
          <div class="info-panel">
            <div class="info-item">
              <span class="info-label">体数据尺寸:</span>
              <span class="info-value">
                {{ volumeData.dimensions[0] }} × {{ volumeData.dimensions[1] }} × {{ volumeData.dimensions[2] }}
              </span>
              </div>
            <div class="info-item">
              <span class="info-label">体素间距:</span>
              <span class="info-value">
                {{ volumeData.spacing[0].toFixed(2) }} × 
                {{ volumeData.spacing[1].toFixed(2) }} × 
                {{ volumeData.spacing[2].toFixed(2) }} mm
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">总切片数:</span>
              <span class="info-value">{{ volumeData.slices }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { orthancService } from '@/services/orthanc.service'

// 体数据接口
interface VolumeData {
  dimensions: [number, number, number]  // [width, height, depth]
  spacing: [number, number, number]     // [x, y, z] spacing in mm
  origin: [number, number, number]      // [x, y, z] origin
  slices: number
  totalSize: number
  imageData: ImageData[]
}

// 响应式数据
const orthancConnected = ref(false)
const loading = ref(false)
const loadProgress = ref(0)
const availableSeries = ref<any[]>([])
const selectedSeriesId = ref('')
const volumeData = ref<VolumeData | null>(null)
const syncEnabled = ref(true)
const loadingMessage = ref('准备加载...')  // 加载状态消息
const isProgressiveLoading = ref(false)  // 是否正在渐进式加载

// Canvas 引用
const axialCanvas = ref<HTMLCanvasElement | null>(null)
const coronalCanvas = ref<HTMLCanvasElement | null>(null)
const sagittalCanvas = ref<HTMLCanvasElement | null>(null)

// 当前切片索引
const currentSlices = ref({
  axial: 0,
  coronal: 0,
  sagittal: 0
})

// 测试连接
const testConnection = async () => {
  try {
    orthancConnected.value = await orthancService.testConnection()
    console.log(`✅ Orthanc连接状态: ${orthancConnected.value}`)
  } catch (error) {
    console.error('❌ 连接测试失败:', error)
    orthancConnected.value = false
  }
}

// 加载可用系列
const loadAvailableSeries = async () => {
  try {
    loading.value = true
    console.log('📥 加载可用系列列表...')
    
    const studies = await orthancService.getStudies()
    const allSeries = []
    
    for (const study of studies) {
      for (const seriesId of study.Series || []) {
        try {
          const response = await fetch(`/api/orthanc/series/${seriesId}`)
          const seriesData = await response.json()
          allSeries.push({
            id: seriesId,
            ...seriesData
          })
        } catch (error) {
          console.warn(`⚠️ 获取系列失败: ${seriesId}`)
        }
      }
    }
    
    availableSeries.value = allSeries
    console.log(`✅ 加载了 ${allSeries.length} 个系列`)
  } catch (error) {
    console.error('❌ 加载系列列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载体数据（支持渐进式加载）
const loadVolumeData = async (progressive: boolean = true) => {
  if (!selectedSeriesId.value) return
  
  loading.value = true
  loadProgress.value = 0
  isProgressiveLoading.value = progressive
  
  try {
    loadingMessage.value = '正在连接服务器...'
    console.log(`📦 开始加载体数据: ${selectedSeriesId.value}`)
    console.log(`🎯 加载模式: ${progressive ? '渐进式' : '完整'}加载`)
    
    // 获取系列信息
    const response = await fetch(`/api/orthanc/series/${selectedSeriesId.value}`)
    const seriesData = await response.json()
    
    const instances = seriesData.Instances || []
    if (instances.length === 0) {
      throw new Error('该系列没有实例')
    }
    
    console.log(`📊 系列包含 ${instances.length} 个实例`)
    
    // 第一步：并发获取所有实例的元数据用于排序
    type InstanceInfo = {
      id: string
      instanceNumber: number
      imagePosition: number[]
      sliceLocation: number
      tags?: any  // 缓存tags数据，避免重复请求
    }
    
    console.log('📥 第1步：并发获取实例元数据...')
    console.time('⏱️ 元数据加载耗时')
    
    // 使用Promise.all并发获取所有元数据
    const metadataPromises = instances.map((instanceId: string, index: number) => 
      fetch(`/api/orthanc/instances/${instanceId}/simplified-tags`)
        .then(res => res.json())
        .then(tags => {
          // 更新进度
          loadProgress.value = Math.round(((index + 1) / instances.length) * 50)
          
          // 获取实例编号
          const instanceNumber = tags.InstanceNumber ? parseInt(tags.InstanceNumber) : index
          
          // 获取图像位置（用于排序）
          let imagePosition = [0, 0, 0]
          if (tags.ImagePositionPatient) {
            imagePosition = tags.ImagePositionPatient.split('\\').map(parseFloat)
          }
          
          // 获取切片位置
          const sliceLocation = tags.SliceLocation ? parseFloat(tags.SliceLocation) : 0
          
          return {
            id: instanceId,
            instanceNumber,
            imagePosition,
            sliceLocation,
            tags  // 缓存tags，后续可以复用
          }
        })
        .catch(() => {
          console.warn(`⚠️ 无法获取实例 ${instanceId} 的元数据，使用默认值`)
          return {
            id: instanceId,
            instanceNumber: index,
            imagePosition: [0, 0, index],
            sliceLocation: index,
            tags: null
          }
        })
    )
    
    const instanceInfos = await Promise.all(metadataPromises)
    console.timeEnd('⏱️ 元数据加载耗时')
    console.log(`✅ 并发加载了 ${instanceInfos.length} 个实例的元数据`)
    
    // 按照Z坐标排序（或实例编号）
    instanceInfos.sort((a, b) => {
      // 优先使用图像位置的Z坐标
      if (a.imagePosition[2] !== b.imagePosition[2]) {
        return a.imagePosition[2] - b.imagePosition[2]
      }
      // 其次使用切片位置
      if (a.sliceLocation !== b.sliceLocation) {
        return a.sliceLocation - b.sliceLocation
      }
      // 最后使用实例编号
      return a.instanceNumber - b.instanceNumber
    })
    
    console.log('✅ 实例已按空间位置排序')
    console.log(`   首切片位置: ${instanceInfos[0].imagePosition[2].toFixed(2)}`)
    console.log(`   末切片位置: ${instanceInfos[instanceInfos.length - 1].imagePosition[2].toFixed(2)}`)
    
    // 第二步：智能加载图像数据
    console.log('📥 第2步：智能并发加载图像数据...')
    console.time('⏱️ 图像加载耗时')
    
    let firstImage: any = null
    let spacing = [1, 1, 1]
    let origin = [0, 0, 0]
    
    // 提前计算spacing（使用第一个实例的缓存tags）
    const firstInstanceInfo = instanceInfos[0]
    origin = firstInstanceInfo.imagePosition
    
    if (firstInstanceInfo.tags) {
      const tags = firstInstanceInfo.tags
      
      // 获取像素间距
      if (tags.PixelSpacing) {
        const pixelSpacing = tags.PixelSpacing.split('\\').map(parseFloat)
        spacing[0] = pixelSpacing[0] || 1
        spacing[1] = pixelSpacing[1] || 1
      }
      
      // 计算切片间距（使用相邻切片的位置差）
      if (instanceInfos.length > 1) {
        const sliceDiff = Math.abs(
          instanceInfos[1].imagePosition[2] - instanceInfos[0].imagePosition[2]
        )
        if (sliceDiff > 0) {
          spacing[2] = sliceDiff
        } else if (tags.SliceThickness) {
          spacing[2] = parseFloat(tags.SliceThickness)
        }
      } else if (tags.SliceThickness) {
        spacing[2] = parseFloat(tags.SliceThickness)
      }
      
      console.log(`📐 像素间距: [${spacing[0].toFixed(2)}, ${spacing[1].toFixed(2)}, ${spacing[2].toFixed(2)}] mm`)
    }
    
    // 根据切片数量动态调整并发数
    const optimalConcurrency = instanceInfos.length < 50 ? 10 : 8
    console.log(`🔧 使用并发数: ${optimalConcurrency}`)
    
    // 图像加载函数
    const loadSingleImage = async (instanceInfo: typeof instanceInfos[0], index: number): Promise<ImageData> => {
      const instanceId = instanceInfo.id
      
      try {
        // 获取实例的预览图像
        const imgResponse = await fetch(`/api/orthanc/instances/${instanceId}/preview`)
        const imgBlob = await imgResponse.blob()
        const imgUrl = URL.createObjectURL(imgBlob)
        
        // 加载图像
        const img = await loadImage(imgUrl)
        
        if (index === 0) {
          firstImage = img
        }
        
        // 将图像转换为 ImageData
        const canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        const ctx = canvas.getContext('2d')!
        ctx.drawImage(img, 0, 0)
        const imageData = ctx.getImageData(0, 0, img.width, img.height)
        
        // 清理临时URL
        URL.revokeObjectURL(imgUrl)
        
        return imageData
      } catch (error) {
        console.error(`❌ 加载实例失败 ${instanceId}:`, error)
        // 返回空的ImageData作为占位
        return new ImageData(1, 1)
      }
    }
    
    let imageDataArray: ImageData[] = []
    
    if (progressive && instanceInfos.length > 10) {
      // 渐进式加载：先加载关键帧
      loadingMessage.value = '快速加载关键帧...'
      console.log('🎯 阶段1: 加载关键帧')
      
      const keyFrameIndices = getKeyFrameIndices(instanceInfos.length, 7)
      console.log(`📍 关键帧索引: [${keyFrameIndices.join(', ')}]`)
      
      // 初始化数组
      imageDataArray = new Array(instanceInfos.length)
      
      // 加载关键帧
      let keyFrameCount = 0
      await promisePool(
        keyFrameIndices,
        async (frameIndex) => {
          const imageData = await loadSingleImage(instanceInfos[frameIndex], frameIndex)
          imageDataArray[frameIndex] = imageData
          keyFrameCount++
          loadProgress.value = 50 + Math.round((keyFrameCount / keyFrameIndices.length) * 25)
          loadingMessage.value = `关键帧 ${keyFrameCount}/${keyFrameIndices.length}`
          return imageData
        },
        optimalConcurrency
      )
      
      console.log('✅ 关键帧加载完成，准备渲染预览...')
      
      // 创建临时体数据用于预览
      const tempVolumeData: VolumeData = {
        dimensions: [firstImage.width, firstImage.height, instanceInfos.length],
        spacing: spacing as [number, number, number],
        origin: origin as [number, number, number],
        slices: instanceInfos.length,
        totalSize: firstImage.width * firstImage.height * instanceInfos.length,
        imageData: imageDataArray
      }
      
      volumeData.value = tempVolumeData
      
      // 初始化切片位置到中间关键帧
      const middleKeyFrame = keyFrameIndices[Math.floor(keyFrameIndices.length / 2)]
      currentSlices.value = {
        axial: middleKeyFrame,
        coronal: Math.floor(firstImage.height / 2),
        sagittal: Math.floor(firstImage.width / 2)
      }
      
      await nextTick()
      renderAllViews()
      
      console.log('🎬 预览已显示，后台加载剩余帧...')
      loadingMessage.value = '后台加载完整数据...'
      
      // 后台加载剩余帧
      const remainingIndices = Array.from({ length: instanceInfos.length }, (_, i) => i)
        .filter(i => !keyFrameIndices.includes(i))
      
      console.log(`🎯 阶段2: 后台加载剩余 ${remainingIndices.length} 帧`)
      
      let remainingCount = 0
      await promisePool(
        remainingIndices,
        async (frameIndex) => {
          const imageData = await loadSingleImage(instanceInfos[frameIndex], frameIndex)
          imageDataArray[frameIndex] = imageData
          remainingCount++
          loadProgress.value = 75 + Math.round((remainingCount / remainingIndices.length) * 25)
          loadingMessage.value = `后台加载 ${remainingCount}/${remainingIndices.length}`
          return imageData
        },
        optimalConcurrency
      )
      
      console.log('✅ 所有帧加载完成')
      
      // 强制最终渲染，去除未加载切片的占位条纹
      loadingMessage.value = '渲染完整数据...'
      await nextTick()
      renderAllViews()
      
    } else {
      // 完整加载模式
      loadingMessage.value = '加载所有图像...'
      let completedCount = 0
      
      imageDataArray = await promisePool(
        instanceInfos,
        async (instanceInfo, index) => {
          const imageData = await loadSingleImage(instanceInfo, index)
          completedCount++
          loadProgress.value = 50 + Math.round((completedCount / instanceInfos.length) * 50)
          loadingMessage.value = `加载图像 ${completedCount}/${instanceInfos.length}`
          return imageData
        },
        optimalConcurrency
      )
    }
    
    console.timeEnd('⏱️ 图像加载耗时')
    
    if (imageDataArray.length === 0) {
      throw new Error('没有成功加载任何图像')
    }
    
    // 创建体数据对象
    volumeData.value = {
      dimensions: [firstImage.width, firstImage.height, imageDataArray.length],
      spacing: spacing as [number, number, number],
      origin: origin as [number, number, number],
      slices: imageDataArray.length,
      totalSize: firstImage.width * firstImage.height * imageDataArray.length,
      imageData: imageDataArray
    }
    
    // 初始化切片位置
    currentSlices.value = {
      axial: Math.floor(imageDataArray.length / 2),
      coronal: Math.floor(firstImage.height / 2),
      sagittal: Math.floor(firstImage.width / 2)
    }
    
    console.log(`✅ 体数据加载完成:`, volumeData.value)
    
    // 渲染初始视图
    await nextTick()
    renderAllViews()
    
  } catch (error) {
    console.error('❌ 加载体数据失败:', error)
    alert(`加载体数据失败: ${error}`)
  } finally {
    loading.value = false
    loadProgress.value = 0
  }
}

// 辅助函数：加载图像
const loadImage = (url: string): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => resolve(img)
    img.onerror = reject
    img.src = url
  })
}

// 辅助函数：智能并发池控制（优化版）
const promisePool = async <T, R>(
  items: T[],
  asyncFn: (item: T, index: number) => Promise<R>,
  concurrency: number = 8
): Promise<R[]> => {
  const results: R[] = new Array(items.length)
  let index = 0
  
  // 工作函数：处理单个任务
  const worker = async (): Promise<void> => {
    while (index < items.length) {
      const currentIndex = index++
      try {
        results[currentIndex] = await asyncFn(items[currentIndex], currentIndex)
      } catch (error) {
        console.error(`Task ${currentIndex} failed:`, error)
        // 继续处理下一个，不中断整个流程
      }
    }
  }
  
  // 创建并发工作池
  const workers = Array(Math.min(concurrency, items.length))
    .fill(null)
    .map(() => worker())
  
  await Promise.all(workers)
  return results
}

// 辅助函数：获取关键帧索引（用于渐进式加载）
const getKeyFrameIndices = (totalFrames: number, keyFrameCount: number = 5): number[] => {
  if (totalFrames <= keyFrameCount) {
    return Array.from({ length: totalFrames }, (_, i) => i)
  }
  
  const indices: number[] = []
  const step = Math.floor(totalFrames / (keyFrameCount - 1))
  
  // 添加关键帧：首、中间几个、尾
  for (let i = 0; i < keyFrameCount; i++) {
    const index = Math.min(i * step, totalFrames - 1)
    if (!indices.includes(index)) {
      indices.push(index)
    }
  }
  
  return indices.sort((a, b) => a - b)
}

// 渲染所有视图
const renderAllViews = () => {
  if (!volumeData.value) return
  
  renderAxialView()
  renderCoronalView()
  renderSagittalView()
}

// 渲染轴位视图 (Axial - 横断面)
const renderAxialView = () => {
  if (!volumeData.value || !axialCanvas.value) return
  
  const canvas = axialCanvas.value
  const ctx = canvas.getContext('2d')!
  const sliceIndex = currentSlices.value.axial
  
  if (sliceIndex < volumeData.value.imageData.length) {
    const imageData = volumeData.value.imageData[sliceIndex]
    
    // 检查imageData是否存在（渐进式加载时可能还未加载）
    if (imageData && imageData.width && imageData.height) {
      canvas.width = imageData.width
      canvas.height = imageData.height
      ctx.putImageData(imageData, 0, 0)
    } else {
      // 显示加载占位图
      canvas.width = 512
      canvas.height = 512
      ctx.fillStyle = '#1a1a1a'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.fillStyle = '#666'
      ctx.font = '16px Arial'
      ctx.textAlign = 'center'
      ctx.fillText('加载中...', canvas.width / 2, canvas.height / 2)
    }
  }
}

// 渲染冠状位视图 (Coronal - 冠状面)
const renderCoronalView = () => {
  if (!volumeData.value || !coronalCanvas.value) return
  
  const canvas = coronalCanvas.value
  const ctx = canvas.getContext('2d')!
  const y = currentSlices.value.coronal
  
  // 从体数据中提取冠状切片
  const [width, , depth] = volumeData.value.dimensions
  const coronalImageData = ctx.createImageData(width, depth)
  
  // 修正：从上到下遍历（z轴反向），使图像正向显示
  let hasValidData = false
  for (let z = 0; z < depth; z++) {
    const sliceData = volumeData.value.imageData[depth - 1 - z]  // 反向读取切片
    
    // 检查切片数据是否存在
    if (sliceData && sliceData.data && sliceData.width === width && y < sliceData.height) {
      hasValidData = true
      for (let x = 0; x < width; x++) {
        const srcIndex = (y * width + x) * 4
        const dstIndex = (z * width + x) * 4
        
        // 确保源索引在有效范围内
        if (srcIndex + 3 < sliceData.data.length) {
          coronalImageData.data[dstIndex] = sliceData.data[srcIndex]
          coronalImageData.data[dstIndex + 1] = sliceData.data[srcIndex + 1]
          coronalImageData.data[dstIndex + 2] = sliceData.data[srcIndex + 2]
          coronalImageData.data[dstIndex + 3] = sliceData.data[srcIndex + 3]
        } else {
          // 超出范围，填充黑色
          coronalImageData.data[dstIndex] = 0
          coronalImageData.data[dstIndex + 1] = 0
          coronalImageData.data[dstIndex + 2] = 0
          coronalImageData.data[dstIndex + 3] = 255
        }
      }
    } else {
      // 填充黑色（未加载的切片或尺寸不匹配）
      for (let x = 0; x < width; x++) {
        const dstIndex = (z * width + x) * 4
        coronalImageData.data[dstIndex] = 0
        coronalImageData.data[dstIndex + 1] = 0
        coronalImageData.data[dstIndex + 2] = 0
        coronalImageData.data[dstIndex + 3] = 255
      }
    }
  }
  
  if (hasValidData) {
    canvas.width = width
    canvas.height = depth
    ctx.putImageData(coronalImageData, 0, 0)
  }
}

// 渲染矢状位视图 (Sagittal - 矢状面)
const renderSagittalView = () => {
  if (!volumeData.value || !sagittalCanvas.value) return
  
  const canvas = sagittalCanvas.value
  const ctx = canvas.getContext('2d')!
  const x = currentSlices.value.sagittal
  
  // 从体数据中提取矢状切片
  const [width, height, depth] = volumeData.value.dimensions
  const sagittalImageData = ctx.createImageData(height, depth)
  
  // 修正：从上到下遍历（z轴反向），使图像正向显示
  let hasValidData = false
  for (let z = 0; z < depth; z++) {
    const sliceData = volumeData.value.imageData[depth - 1 - z]  // 反向读取切片
    
    // 检查切片数据是否存在
    if (sliceData && sliceData.data && sliceData.width === width && x < sliceData.width) {
      hasValidData = true
      for (let y = 0; y < height; y++) {
        const srcIndex = (y * width + x) * 4
        const dstIndex = (z * height + y) * 4
        
        // 确保源索引在有效范围内
        if (srcIndex + 3 < sliceData.data.length) {
          sagittalImageData.data[dstIndex] = sliceData.data[srcIndex]
          sagittalImageData.data[dstIndex + 1] = sliceData.data[srcIndex + 1]
          sagittalImageData.data[dstIndex + 2] = sliceData.data[srcIndex + 2]
          sagittalImageData.data[dstIndex + 3] = sliceData.data[srcIndex + 3]
        } else {
          // 超出范围，填充黑色
          sagittalImageData.data[dstIndex] = 0
          sagittalImageData.data[dstIndex + 1] = 0
          sagittalImageData.data[dstIndex + 2] = 0
          sagittalImageData.data[dstIndex + 3] = 255
        }
      }
    } else {
      // 填充黑色（未加载的切片或尺寸不匹配）
      for (let y = 0; y < height; y++) {
        const dstIndex = (z * height + y) * 4
        sagittalImageData.data[dstIndex] = 0
        sagittalImageData.data[dstIndex + 1] = 0
        sagittalImageData.data[dstIndex + 2] = 0
        sagittalImageData.data[dstIndex + 3] = 255
      }
    }
  }
  
  if (hasValidData) {
    canvas.width = height
    canvas.height = depth
    ctx.putImageData(sagittalImageData, 0, 0)
  }
}

// 鼠标滚轮事件处理
const onMouseWheel = (view: 'axial' | 'coronal' | 'sagittal', event: WheelEvent) => {
  event.preventDefault()
  
  if (!volumeData.value) return
  
  const delta = event.deltaY > 0 ? 1 : -1
  
  if (view === 'axial') {
    currentSlices.value.axial = Math.max(0, Math.min(
      volumeData.value.dimensions[2] - 1,
      currentSlices.value.axial + delta
    ))
    renderAxialView()
  } else if (view === 'coronal') {
    currentSlices.value.coronal = Math.max(0, Math.min(
      volumeData.value.dimensions[1] - 1,
      currentSlices.value.coronal + delta
    ))
    renderCoronalView()
  } else if (view === 'sagittal') {
    currentSlices.value.sagittal = Math.max(0, Math.min(
      volumeData.value.dimensions[0] - 1,
      currentSlices.value.sagittal + delta
    ))
    renderSagittalView()
  }
}

// 切换同步
const toggleSync = () => {
  syncEnabled.value = !syncEnabled.value
  console.log(`🔄 同步模式: ${syncEnabled.value ? '开启' : '关闭'}`)
}

// 重置视图
const resetView = () => {
  if (!volumeData.value) return
  
  currentSlices.value = {
    axial: Math.floor(volumeData.value.dimensions[2] / 2),
    coronal: Math.floor(volumeData.value.dimensions[1] / 2),
    sagittal: Math.floor(volumeData.value.dimensions[0] / 2)
  }
  
  renderAllViews()
  console.log('🔄 视图已重置')
}

// 生命周期
onMounted(async () => {
  console.log('🚀 初始化 DICOM MPR 三视图查看器')
  
  await testConnection()
  
  if (orthancConnected.value) {
    await loadAvailableSeries()
  }
})
</script>

<style scoped>
.dicom-mpr-page {
  height: 100%;
  width: 100%;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 工具栏样式 */
.toolbar {
  height: 60px;
  background: white;
  border-bottom: 2px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title {
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
}

.page-subtitle {
  font-size: 12px;
  color: #6c757d;
  font-weight: 400;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.status-indicator {
  font-size: 12px;
}

.status-text {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.sync-btn, .reset-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.sync-btn:hover, .reset-btn:hover {
  background: #0056b3;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 123, 255, 0.3);
}

.sync-btn.active {
  background: #28a745;
}

.sync-btn.active:hover {
  background: #218838;
}

.sync-btn:disabled, .reset-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
  transform: none;
}

/* 主内容区 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧系列选择面板 */
.series-panel {
  width: 320px;
  background: white;
  border-right: 2px solid #e9ecef;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
}

.panel-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8f9fa;
}

.panel-header h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: #2c3e50;
}

.series-count {
  font-size: 11px;
  color: #fff;
  background: #007bff;
  padding: 4px 10px;
  border-radius: 12px;
  font-weight: 600;
}

.series-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.series-item {
  border: 2px solid #e9ecef;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  background: white;
}

.series-item:hover {
  border-color: #007bff;
  background: #f8f9ff;
  transform: translateX(2px);
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
}

.series-item.active {
  border-color: #007bff;
  background: #e7f3ff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.2);
}

.series-info {
  flex: 1;
}

.series-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 6px;
  line-height: 1.4;
}

.series-details {
  display: flex;
  gap: 12px;
  margin-bottom: 4px;
}

.detail-item {
  font-size: 12px;
  color: #6c757d;
  background: #f8f9fa;
  padding: 2px 8px;
  border-radius: 4px;
}

.series-id {
  font-size: 11px;
  color: #999;
  font-family: 'Courier New', monospace;
  margin-top: 4px;
}

.series-selected-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: #28a745;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
}

.empty-series {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.5;
}

.empty-text {
  font-size: 13px;
  color: #6c757d;
}

.panel-footer {
  padding: 16px;
  border-top: 1px solid #e9ecef;
  background: white;
}

.load-btn {
  width: 100%;
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: white;
  border: none;
  padding: 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.load-btn:hover {
  background: linear-gradient(135deg, #218838 0%, #1ba87d 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(40, 167, 69, 0.4);
}

.load-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
  opacity: 0.8;
}

.btn-icon {
  font-size: 16px;
  margin-right: 6px;
  display: inline-block;
}

.loading-spinner {
  display: inline-block;
  animation: spin 1.5s linear infinite;
  margin-right: 8px;
  font-size: 16px;
}

.progress-text {
  display: inline-block;
  margin-top: 4px;
  font-size: 12px;
  opacity: 0.9;
  font-weight: 700;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 右侧查看器面板 */
.viewer-panel {
  flex: 1;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.empty-viewer {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
}

.empty-content {
  text-align: center;
  padding: 60px 40px;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
  opacity: 0.3;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.empty-subtitle {
  font-size: 14px;
  color: #6c757d;
  line-height: 1.6;
}

/* MPR 查看器 */
.mpr-viewer {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow: hidden;
}

/* MPR 视图网格 */
.mpr-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  flex: 1;
  margin-bottom: 16px;
  overflow: hidden;
}

.viewport {
  background: white;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.viewport-header {
  padding: 10px 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.coronal-view .viewport-header {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.sagittal-view .viewport-header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.viewport-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.slice-info {
  font-size: 12px;
  background: rgba(255, 255, 255, 0.2);
  padding: 3px 10px;
  border-radius: 12px;
  font-weight: 500;
}

.viewport-content {
  flex: 1;
  position: relative;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.dicom-canvas {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  cursor: crosshair;
}

.viewport-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

/* 方向标签 */
.orientation-labels {
  position: relative;
  width: 100%;
  height: 100%;
}

.orientation-labels span {
  position: absolute;
  color: #00ff00;
  font-size: 12px;
  font-weight: 600;
  text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
  font-family: Arial, sans-serif;
}

.label-top {
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
}

.label-bottom {
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
}

.label-left {
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.label-right {
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.viewport-slider {
  padding: 8px 12px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.slice-slider {
  width: 100%;
  cursor: pointer;
}

/* 底部信息面板 */
.info-panel {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px 20px;
  display: flex;
  gap: 32px;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.info-label {
  font-size: 13px;
  color: #6c757d;
  font-weight: 600;
}

.info-value {
  font-size: 13px;
  color: #2c3e50;
  font-weight: 500;
  font-family: 'Courier New', monospace;
  background: #f8f9fa;
  padding: 4px 10px;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .mpr-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .viewport:last-child {
    grid-column: 1 / -1;
  }
}

@media (max-width: 1024px) {
  .series-panel {
    width: 280px;
  }
  
  .mpr-grid {
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .series-panel {
    width: 100%;
    max-height: 300px;
  }
  
  .mpr-grid {
    grid-template-columns: 1fr;
  }
  
  .viewport:last-child {
    grid-column: 1;
  }
  
  .info-panel {
    flex-direction: column;
    gap: 12px;
  }
}

/* 滚动条美化 */
.series-list::-webkit-scrollbar {
  width: 6px;
}

.series-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.series-list::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.series-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>
